/** 将带md5信息的json合并 */
export function compactMd5Json(obj: string | any) {
    let json = {}
    if (typeof obj == 'string') {
        json = JSON.parse(obj);
    } else {
        json = obj;
    }
    let result = {};
    for (let key in json) {
        let paths = key.split('/');
        let src = json[key];
        let t = src.split('.');
        let s = t[t.length - 2] + '';
        let fs = s.substr(s.length - 8)
        setObj(result, paths, fs);
    }

    return result;
}

function setObj(obj: any, keys: string[], value: string) {
    for (let i = 0, n = keys.length; i < n; i++) {
        let k = keys[i]
        if (i + 1 >= n) {
            obj[k] = value;
            break;
        }
        if (!obj[k]) {
            obj[k] = {}
        }
        obj = obj[k];
    }
}

/** 将已经合并的带有md5信息的json，拍扁 */
export function flatteningMd5Json(obj: string | any) {
    let json = {}
    if (typeof obj == 'string') {
        json = JSON.parse(obj);
    } else {
        json = obj;
    }
    let result = {}
    flatten(json, result, '');
    return result;
}

function flatten(json: any, result: any, crtKey: string) {
    for (let key in json) {
        let obj = json[key];
        if (typeof obj == 'string') {
            crtKey += key;
            let temp = crtKey.split('.');
            let last = temp[temp.length - 1];
            let s = crtKey.substr(0, crtKey.length - last.length - 1);
            result[crtKey] = `${s}_${obj}.${last}`;
            crtKey = crtKey.substr(0, crtKey.length - key.length);
            continue;
        }
        else {
            crtKey += (key + '/');
        }
        flatten(obj, result, crtKey);
        crtKey = crtKey.substr(0, crtKey.length - key.length - 1);
    }
}